﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using InformationSystem.BLL.Core.Model;
using InformationSystem.BLL.Core.Dao;
using System.IO;

namespace InformationSystem.BLL.Core.Service.Impl
{
    public class InformationServiceImpl : IInformationService
    {
        /*
         基于共享式的信息存储方案
         * 发送的信息不会每人得到一份原始副本，这样太占硬盘空间，特别是群发邮件的附件等
         * 以500人年级的举例，1M的附件会被放大到500M，但管理轻松
         * 采用共享式，接收者有对此文件引用，除非最后一个引用者删除此附件
         * 否则附件一直存在，管理逻辑有点提升
         * 现在采用第二种方案
         */

        public IInformationDao InformationDao { get; set; }
        public IUserDao UserDao { get; set; }
        public bool SendMail(Mail mail)
        {
            //STEP 1 从目的接收者中分析组列表和用户列表，除去不可到达用户以及组,没有接收用户，返回
            //SETP 2 存储邮件主体，返回邮件ID号
            //STEP 3 存储收件组合收件人
            //STEP 4 储存附件文件名信息 IF Existed
            mail.RecvString = mail.RecvString.TrimEnd(',');
            string[] tmprecv = mail.RecvString.Split(',');
            foreach (string item in tmprecv)
            {
                int start = item.IndexOf('[');
                int last = item.IndexOf(']');
                if (start == -1 || last == -1) continue;
                string id = item.Substring(start + 1, last - start - 1);
                string name = item.Substring(0, start);
                if (id.Trim() == string.Empty) continue;
                //检查这个号属于组还是属于一个用户,暂时检查是否属于用户
                //string tmpid=id.tr
                if (UserDao.CheckUserExisted(id))
                {
                    if (mail.RecvUserList.Find(val => val.UserID == id) != null)
                        continue;
                    RecvUser ru = new RecvUser();
                    ru.UserID = id;
                    ru.UserName = name;
                    mail.RecvUserList.Add(ru);
                }
                else
                {
                    mail.Msg += string.Format("{0} 发送不可到达，请检查输入格式及用户是否存在 \r\n", item);
                }
                //如果不存在这样的信息，存入发送不可达信息列表
                //根据相应信息存入合适的表
            }
            if (mail.RecvUserList.Count == 0)
            {
                mail.Msg = "没有任何有效接收者，请重新检查，邮件发送失败!";
                return false;
            }
            //检查接受对象数量不为空，否则返回False,发送失败
            InformationDao.SendMail(mail);
            return true;
        }

        public bool SaveMail(Mail mail)
        {

            return true;
        }

        public IList<Mail> GetMailSendList(string sendUserID)
        {
            IList<Mail> list = InformationDao.GetMailSendList(sendUserID);
            DateTime now = DateTime.Now.Date;
            foreach (var item in list)
            {
                int days = (now - item.SendTime.Date).Days;
                if (days < 1)
                {
                    item.GroupTip = "今天";
                }
                else if (days >= 1 && days < 7)
                {
                    item.GroupTip = "一周内";
                }
                else
                {
                    item.GroupTip = "更久";
                }
            }
            return list;
        }

        public IList<Mail> GetMailRecvList(string recvuserID)
        {
            IList<Mail> list = InformationDao.GetMailRecvList(recvuserID);
            DateTime now = DateTime.Now.Date;
            foreach (var item in list)
            {
                int days = (now - item.SendTime.Date).Days;
                if (days < 1)
                {
                    item.GroupTip = "今天";
                }
                else if (days >= 1 && days < 7)
                {
                    item.GroupTip = "一周内";
                }
                else
                {
                    item.GroupTip = "更久";
                }
            }
            return list;
        }

        public IList<Mail> GetMailDraftList(string senduserID)
        {
            throw new NotImplementedException();
        }


        public bool DeleteMailSent(int mailID, string senduserid, string appRunPath)
        {
            IList<RecvUser> userlist = InformationDao.GetMailRecvUserList(mailID);
            IList<Attachment> attachmentlist = InformationDao.GetMailAttachments(mailID);
            int num = attachmentlist.Count;

            if (userlist.Count == 0)
            {
                if (num != 0)
                {
                    for (int index = 0; index < num; index++)
                    {
                        string attpath = appRunPath + @"\" + attachmentlist[index].SavedFileName.ToString();

                        if (File.Exists(attpath))
                        {
                            File.Delete(attpath);
                        }
                    }
                    InformationDao.DeleteMailAttachment(mailID);
                }
                return InformationDao.DeleteMailSent(mailID, senduserid);
            }
            else
            {
                return InformationDao.UpdateMailStatus(mailID, MailStatus.Deleted);
            }


        }

        public bool DeleteMailRecvd(int mailID, string recvuserid)
        {
            return InformationDao.DeleteMailRecvd(mailID, recvuserid);
        }

        public Mail GetMailDetailByID(int mailID, string userid)
        {
            //需要在此处进行权限控制
            //如果发信者和接收者都不含有该ID，返回空Mail
            Mail mail = InformationDao.GetMailDetailByID(mailID);
            if (mail == null)
            {
                Mail tmpmail = new Mail();
                tmpmail.Msg = "无法获取此邮件的详细信息!";
            }
            //如果有附件，读取附件信息
            mail.AttachmentList = InformationDao.GetMailAttachments(mailID);
            InformationDao.UpdateMailRead(mailID, userid);
            return mail;
        }

        public Attachment GetMailAttachment(int mailid, int fileid)
        {
            return InformationDao.GetMailAttachment(mailid, fileid);
        }


        public bool SendAffiche(Affiche affiche)
        {
            return this.InformationDao.SendAffiche(affiche);
        }

        public bool DeleteAfficheByID(int afficheID, string userid, string path)
        {
            Affiche tmp = InformationDao.GetAffiche(afficheID);
            //信息不存在
            if (tmp == null) return false;
            //权限检查
            if (tmp.CommitUserID != userid) return false;
            IList<Attachment> attachmentlist = InformationDao.GetAfficheAttachments(afficheID);
            if (attachmentlist != null)
            {
                foreach (var item in attachmentlist)
                {
                    string attpath = Path.Combine(path, item.SavedFileName);
                    if (File.Exists(attpath))
                    {
                        File.Delete(attpath);
                    }
                }
            }
            return InformationDao.DeleteAfficheByID(afficheID);
        }

        public IList<Affiche> GetRecvAfficheList(LoginUser user, int recordcount)
        {
            IList<Affiche> list = InformationDao.GetRecvAfficheList(user, recordcount);
            DateTime now = DateTime.Now.Date;
            foreach (var item in list)
            {
                int days = (now - item.SendTime.Date).Days;
                if (days < 1)
                {
                    item.GroupTip = "今天";
                }
                else if (days >= 1 && days < 7)
                {
                    item.GroupTip = "一周内";
                }
                else
                {
                    item.GroupTip = "更久";
                }
            }
            return list;
        }

        public IList<Affiche> GetSentAfficheList(LoginUser user)
        {
            IList<Affiche> list = InformationDao.GetSentAfficheList(user);
            DateTime now = DateTime.Now.Date;
            foreach (var item in list)
            {
                int days = (now - item.SendTime.Date).Days;
                if (days < 1)
                {
                    item.GroupTip = "今天";
                }
                else if (days >= 1 && days < 7)
                {
                    item.GroupTip = "一周内";
                }
                else
                {
                    item.GroupTip = "更久";
                }
            }
            return list;
        }

        public IList<RecvUser> GetAfficheReadList(int afficheid)
        {
            return InformationDao.GetAfficheReadList(afficheid);
        }


        public Affiche GetAffiche(int afficheid, LoginUser user)
        {
            Affiche tmp = this.InformationDao.GetAffiche(afficheid);
            if (tmp != null)
                tmp.AttachmentList = InformationDao.GetAfficheAttachments(afficheid);
            return tmp;
        }


        public Attachment GetAfficheAttachment(int afficheid, int fileid)
        {
            return InformationDao.GetAfficheAttachment(afficheid, fileid);
        }


        public bool SendWorkInfo(WorkInfo workinfo)
        {
            return this.InformationDao.SendWorkInfo(workinfo);
        }

        public bool DeleteWorkInfoByID(int workInfoid, string userid, string path)
        {
            WorkInfo tmp = InformationDao.GetWorkInfo(workInfoid);
            //信息不存在
            if (tmp == null) return false;
            //权限检查
            if (tmp.CommitUserID != userid) return false;
            IList<Attachment> workinfoattlist = InformationDao.GetWorkInfoAttachments(workInfoid);
            if (workinfoattlist != null)
            {
                foreach (var item in workinfoattlist)
                {
                    string attpath = Path.Combine(path, item.SavedFileName);
                    if (File.Exists(attpath))
                    {
                        File.Delete(attpath);
                    }
                }
            }
            return InformationDao.DeleteWorkInfoByID(workInfoid);
        }

        public IList<WorkInfo> GetRecvWorkInfoList(LoginUser user,int recordcount)
        {
            IList<WorkInfo> list = InformationDao.GetRecvWorkInfoList(user,recordcount);
            DateTime now = DateTime.Now.Date;
            foreach (var item in list)
            {
                int days = (now - item.SendTime.Date).Days;
                if (days < 1)
                {
                    item.GroupTip = "今天";
                }
                else if (days >= 1 && days < 7)
                {
                    item.GroupTip = "一周内";
                }
                else
                {
                    item.GroupTip = "更久";
                }
            }
            return list;
        }

        public IList<WorkInfo> GetSentWorkInfoList(LoginUser user)
        {
            IList<WorkInfo> list = InformationDao.GetSentWorkInfoList(user);
            DateTime now = DateTime.Now.Date;
            foreach (var item in list)
            {
                int days = (now - item.SendTime.Date).Days;
                if (days < 1)
                {
                    item.GroupTip = "今天";
                }
                else if (days >= 1 && days < 7)
                {
                    item.GroupTip = "一周内";
                }
                else
                {
                    item.GroupTip = "更久";
                }
            }
            return list;
        }

        public WorkInfo GetWorkInfo(int workInfoid, LoginUser user)
        {
            WorkInfo tmp = this.InformationDao.GetWorkInfo(workInfoid);
            if (tmp != null)
                tmp.AttachmentList = InformationDao.GetWorkInfoAttachments(workInfoid);
            return tmp;
        }

        public IList<RecvUser> GetWorkInfoReadList(int workinfoid)
        {
            return InformationDao.GetWorkInfoReadList(workinfoid);
        }

        public Attachment GetWorkInfoAttachment(int workInfoid, int fileid)
        {
            return InformationDao.GetWorkInfoAttachment(workInfoid, fileid);
        }


        public bool SendMsg(Msg msg)
        {
            msg.RecvString = msg.RecvString.TrimEnd(',');
            string[] tmprecv = msg.RecvString.Split(',');
            foreach (string item in tmprecv)
            {
                int start = item.IndexOf('[');
                int last = item.IndexOf(']');
                if (start == -1 || last == -1) continue;
                string id = item.Substring(start + 1, last - start - 1);
                string name = item.Substring(0, start);
                if (id.Trim() == string.Empty) continue;
                //检查这个号属于组还是属于一个用户,暂时检查是否属于用户
                if (UserDao.CheckUserExisted(id))
                {
                    //去重复检查
                    if (msg.RecvUserList.Find(val => val.UserID == id) != null)
                        continue;
                    RecvUser ru = new RecvUser();
                    ru.UserID = id;
                    ru.UserName = name;
                    msg.RecvUserList.Add(ru);
                }
                else
                {
                    msg.Msg += string.Format("{0} 发送不可到达，请检查输入格式及用户是否存在 \r\n", item);
                }
                //如果不存在这样的信息，存入发送不可达信息列表
                //根据相应信息存入合适的表
            }
            if (msg.RecvUserList.Count == 0)
            {
                msg.Msg = "没有任何有效接收者，请重新检查，邮件发送失败!";
                return false;
            }
            //检查接受对象数量不为空，否则返回False,发送失败
            InformationDao.SendMsg(msg);
            return true;
        }

        public IList<Msg> GetMsgSendList(string sendUserID)
        {
            IList<Msg> msglist= InformationDao.GetMsgSendList(sendUserID);
            DateTime now = DateTime.Now.Date;
            foreach (var item in msglist)
            {
                int days = (now - item.SendTime.Date).Days;
                if (days < 1)
                {
                    item.GroupTip = "今天";
                }
                else if (days >= 1 && days < 7)
                {
                    item.GroupTip = "一周内";
                }
                else
                {
                    item.GroupTip = "更久";
                }
            }
            return msglist;
        }

        public IList<Msg> GetMsgRecvList(string recvuserID, int recordcount)
        {
            IList<Msg> msglist= InformationDao.GetMsgRecvList(recvuserID,recordcount);
            DateTime now = DateTime.Now.Date;
            foreach (var item in msglist)
            {
                int days = (now - item.SendTime.Date).Days;
                if (days < 1)
                {
                    item.GroupTip = "今天";
                }
                else if (days >= 1 && days < 7)
                {
                    item.GroupTip = "一周内";
                }
                else
                {
                    item.GroupTip = "更久";
                }
            }
            return msglist;
        }

        public bool DeleteMsgSent(int msgID, string senduserid, string appRunPath)
        {
            Msg tmp = InformationDao.GetMsgDetailByID(msgID);
            //信息不存在
            if (tmp == null) return false;
            //权限检查
            if (tmp.SendUserID != senduserid) return false;
            IList<Attachment> msgattlist = InformationDao.GetMsgAttachments(msgID);
            if (msgattlist != null)
            {
                foreach (var item in msgattlist)
                {
                    string attpath = Path.Combine(appRunPath, item.SavedFileName);
                    if (File.Exists(attpath))
                    {
                        File.Delete(attpath);
                    }
                }
            }
            return InformationDao.DeleteMsgSent(msgID);
        }

        public Msg GetMsgDetailByID(int msgID, LoginUser user)
        {
            Msg tmp = InformationDao.GetMsgDetailByID(msgID);
            if (tmp == null) return null;
            tmp.AttachmentList = InformationDao.GetMsgAttachments(msgID);
            IList<RecvUser> trulist = InformationDao.GetMsgRecvUserList(msgID);
            foreach (var item in trulist)
            {
                tmp.RecvUserList.Add(item);
            }
            trulist.Clear();
            return tmp;
        }

        public Attachment GetMsgAttachment(int msgid, int fileid)
        {
            return InformationDao.GetMsgAttachment(msgid, fileid);
        }


        public IList<RecvUser> GetMsgReadList(int msgid)
        {
            return InformationDao.GetMsgReadList(msgid);
        }

        public IList<RecvUser> GetMsgUnReadList(int msgid)
        {
            return InformationDao.GetMsgUnReadList(msgid);
        }


        public void UpdateMsgUserReadStatusToRead(int msgid, string userid)
        {
            this.InformationDao.UpdateMsgUserReadStatusToRead(msgid, userid);
        }


        public void UpdateAfficheUserReadStatus(int afficheid, LoginUser user)
        {
            InformationDao.UpdateAfficheUserReadStatus(afficheid, user);
        }

        public void UpdateWorkInfoUserReadStatus(int workInfoid, LoginUser user)
        {
            InformationDao.UpdateWorkInfoUserReadStatus(workInfoid, user);
        }


        public bool ReplyMsg(int msgid, LoginUser user, string content)
        {
            //首先读取有没有这样的一条Msg
            Msg msg = InformationDao.GetMsgDetailByID(msgid);
            if (msg == null) return false;
            if (msg.SendUserID == user.UserID)
            {
                //DO Update
                InformationDao.ReplyMsg(msgid, user, content);
                return true;
            }
            IList<RecvUser> recvlist = InformationDao.GetMsgRecvUserList(msgid);
            //判断用户是否属于其中一员
            foreach (var item in recvlist)
            {
                if (item.UserID == user.UserID)
                {
                    //Do Update
                    InformationDao.ReplyMsg(msgid, user, content);
                    return true;
                }
            }
            return false;
        }


        public IList<MsgReplyInfo> GetMsgReplyInfoList(int msgid)
        {
            return InformationDao.GetMsgReplyInfoList(msgid);
        }



        public int GetAfficheCountInGrade(LoginUser user)
        {
            return InformationDao.GetAfficheCountInGrade(user);
        }



        public int GetMailUnreadCount(LoginUser user)
        {
            return InformationDao.GetMailUnreadCount(user);
        }
    }
}
